<template>
  <div class="discover-view">
    <!-- 顶部导航菜单 -->
    <div class="top-nav">
      <el-menu 
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        :ellipsis="false"
        @select="handleSelect">
        <el-sub-menu index="1">
          <template #title>创作中心</template>
          <el-menu-item index="1-1">
            <router-link to="/publish" class="nav-link">创作服务</router-link>
          </el-menu-item>
          <el-menu-item index="1-2">
            <router-link to="/livestream" target="_blank" class="nav-link">直播管理</router-link>
          </el-menu-item>
          <el-menu-item index="1-3">
            <router-link to="/computerlive" target="_blank" class="nav-link">电脑直播助手</router-link>
          </el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="2">
          <template #title>业务合作</template>
          <el-menu-item index="2-1">
            <router-link to="/professional" target="_blank" class="nav-link">专业号</router-link>
          </el-menu-item>
          <el-menu-item index="2-2">
            <router-link to="/promot" target="_blank" class="nav-link">推广合作</router-link>
          </el-menu-item>
          <el-menu-item index="2-4">
            <router-link to="/business" target="_blank" class="nav-link">商家入驻</router-link>
          </el-menu-item>
          <el-menu-item index="2-5">
            <router-link to="/MCN" target="_blank" class="nav-link">MCN入驻</router-link>
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item>
          <router-link to="/shop" target="_blank" class="nav-link" style="font-weight: bold" >青商</router-link>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-container">
        <input 
          v-model="searchQuery" 
          placeholder="搜索笔记、用户、标签..." 
          class="search-input"
          @keyup.enter="handleSearch"
          :disabled="isLoading"
        >
        <button 
          class="filter-btn" 
          @click="toggleFilter"
          :disabled="isLoading"
        >
          <FilterIcon class="icon" />
        </button>
      </div>

      <!-- 热门标签骨架屏 -->
      <div v-if="tagStore.isLoading" class="trending-tags skeleton">
        <div class="skeleton-tag" v-for="i in 8" :key="i"></div>
      </div>
      
      <!-- 热门标签 -->
      <div v-else-if="tagStore.tags?.length" class="trending-tags">
        <button 
          v-for="tag in tagStore.tags" 
          :key="tag.id"
          class="tag"
          :class="{ 'active': activeTag === tag.id }"
          @click="toggleTag(tag.id)"
          :disabled="isLoading"
        >
          #{{ tag.name }}
        </button>
      </div>
      
      <div v-else class="empty-tags">
        <p>暂无热门标签</p>
      </div>
    </div>

    <!-- 为你推荐部分 -->
	
	
	
    <div class="section">	
      <div class="section-header">
        <h2 class="section-title">为你推荐</h2>
        <div v-if="currentFilter" class="filter-status">
          <span>当前筛选: {{ currentFilter }}</span>
          <button class="clear-filter" @click="clearFilter">
            <XIcon class="icon" />
          </button>
        </div>
        <button 
          class="refresh-btn" 
          @click="loadRecommendations"
          :disabled="isLoading"
        >
          <RefreshCwIcon class="icon" />
          <span v-if="!isLoading">刷新</span>
          <span v-else>加载中</span>
        </button>
      </div>
      
      <!-- 推荐内容骨架屏 -->
      <div v-if="noteStore.isLoading" class="notes-grid skeleton-grid">
        <div class="skeleton-card" v-for="i in 6" :key="i"></div>
      </div>
      
      <!-- 推荐内容 -->
      <div v-else-if="noteStore.recommendedNotes?.length" class="notes-grid">
        <NoteCard 
          v-for="note in noteStore.recommendedNotes" 
          :key="note.id" 
          :note="note"
          @like="handleLike(note.id)"
          @collect="handleCollect(note.id)"
          @click="openNoteModal(note.id)"
          :is-liking="noteStore.isLoading"
          :is-collecting="collectionStore.isLoading"  
        />
      </div>
      
      <div v-else class="empty-state">
        <p>暂无推荐内容</p>
        <button 
          class="btn-primary" 
          @click="loadRecommendations"
          :disabled="isLoading"
        >
          刷新推荐
        </button>
      </div>
    </div>

    <!-- 附近动态部分 -->
    <div class="section">
      <div class="section-header">
        <h2 class="section-title">附近动态</h2>
        <button 
          class="location-btn" 
          @click="updateLocation"
          :disabled="isLoading"
        >
          <MapPinIcon class="icon" />
          <span>{{ currentLocation || '定位中...' }}</span>
        </button>
      </div>
      
      <!-- 附近动态骨架屏 -->
      <div v-if="isLoading" class="notes-grid skeleton-grid">
        <div class="skeleton-card" v-for="i in 3" :key="i"></div>
      </div>
      
      <!-- 附近动态 -->
      <div v-else-if="noteStore.nearbyNotes?.length" class="notes-grid">
        <NoteCard 
          v-for="note in noteStore.nearbyNotes" 
          :key="note.id" 
          :note="note"
          @like="handleLike(note.id)"
          @collect="handleCollect(note.id)"
          @click="openNoteModal(note.id)"
          :is-liking="noteStore.isLoading"
          :is-collecting="collectionStore.isLoading"
        />
      </div>
      
      <div v-else class="empty-state">
        <p>附近暂无动态</p>
        <button 
          class="btn-primary" 
          @click="updateLocation"
          :disabled="isLoading"
        >
          刷新位置
        </button>
      </div>
    </div>

    <!-- 热门话题部分 -->
    <div class="section">
      <div class="section-header">
        <h2 class="section-title">热门话题</h2>
        <button 
          class="refresh-btn" 
          @click="loadTrendingTopics"
          :disabled="isLoading"
        >
          <RefreshCwIcon class="icon" />
          <span v-if="!isLoading">刷新</span>
          <span v-else>加载中</span>
        </button>
      </div>
      
      <!-- 热门话题骨架屏 -->
      <div v-if="topicStore.isLoading" class="topics-grid skeleton-grid">
        <div class="skeleton-topic" v-for="i in 3" :key="i"></div>
      </div>
      
      <!-- 热门话题 -->
      <div v-else-if="topicStore.trendingTopics?.length" class="topics-grid">
        <div 
          v-for="topic in topicStore.trendingTopics" 
          :key="topic.id"
          class="topic-card"
          @click="viewTopic(topic.id)"
        >
          <div class="topic-image">
            <img 
              :src="getOptimizedImageUrl(topic.cover, 300, 200)" 
              :alt="topic.title"
              @error="handleImageError"
              loading="lazy"
            >
          </div>
          <div class="topic-info">
            <h3 class="topic-title">#{{ topic.title }}</h3>
            <p class="topic-stats">{{ topic.notesCount }} 笔记 · {{ topic.participants }} 人参与</p>
          </div>
        </div>
      </div>
      
      <div v-else class="empty-state">
        <p>暂无热门话题</p>
        <button 
          class="btn-primary" 
          @click="loadTrendingTopics"
          :disabled="isLoading"
        >
          刷新话题
        </button>
      </div>
    </div>

    <!-- 笔记详情弹窗 -->
    <NoteDetailModal
      v-if="showNoteModal"
      :note-id="currentNoteId"
      @close="closeNoteModal"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { 
  FilterIcon, RefreshCwIcon, MapPinIcon, XIcon 
} from 'lucide-vue-next'
import NoteCard from '@/components/common/NoteCard.vue'
import NoteDetailModal from '@/components/common/NoteDetailModal.vue'
import { useNoteStore } from '@/store/notes'
import { useTagStore } from '@/store/tags'
import { useTopicStore } from '@/store/topics'
import { useAuthStore } from '@/store/auth'
import { useCollectionStore} from '@/store/collections'
import { debounce } from 'lodash-es'

const router = useRouter()
const noteStore = useNoteStore()
const tagStore = useTagStore()
const topicStore = useTopicStore()
const authStore = useAuthStore()
const collectionStore = useCollectionStore()

const searchQuery = ref('')
const activeTag = ref(null)
const currentLocation = ref('')
const showFilter = ref(false)
const currentFilter = ref('')
const showNoteModal = ref(false)
const currentNoteId = ref(null)

// 计算加载状态
const isLoading = computed(() => {
  return noteStore.isLoading || 
         tagStore.isLoading || 
         topicStore.isLoading || 
         collectionStore.isLoading
})

onMounted(() => {
  
  loadInitialData()
  
  // 延迟加载非关键数据
  setTimeout(() => {
    loadTrendingTopics()
    updateLocation()
  }, 500)
})

const loadInitialData = async () => {
  try {
    await tagStore.fetchAllTags()
    if (!activeTag.value) await loadRecommendations()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

const loadRecommendations = async () => {
  isLoading.value = true;
  try {
    // 重置筛选状态
    if (activeTag.value) {
      activeTag.value = null
      currentFilter.value = ''
    }
    
    // 加载推荐笔记
    await noteStore.fetchRecentPublicNotes(6)
  } catch (error) {
    console.error('刷新推荐失败:', error)
  } finally {
    isLoading.value = false;
  }
}

const updateLocation = async () => {
  currentLocation.value = '定位中...'
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    noteStore.nearbyNotes = [
      {
        id: 101,
        userId: 1,
        title: '三里屯新开咖啡店',
        content: '周末发现了一家超有格调的咖啡店，拿铁很赞！',
        isPrivate: false,
        coverImageUrl: 'https://picsum.photos/id/64/400/200',
        createdAt: '2025-09-15T10:00:00',
        updatedAt: '2025-09-15T10:00:00',
        nickname: '咖啡达人',
        avatarUrl: 'https://picsum.photos/id/64/100/100',
        likes: 156,
        collects: 23,
        comments: 12,
        isLiked: false,
        isCollected: false,
        tags: ['咖啡', '探店'],
        location: '北京·三里屯'
      },
      {
        id: 102,
        userId: 2,
        title: '798艺术展',
        content: '周末去798看了新展，非常震撼的视觉体验',
        isPrivate: false,
        coverImageUrl: 'https://picsum.photos/id/65/400/200',
        createdAt: '2025-09-14T14:30:00',
        updatedAt: '2025-09-14T14:30:00',
        nickname: '艺术爱好者',
        avatarUrl: 'https://picsum.photos/id/65/100/100',
        likes: 289,
        collects: 45,
        comments: 18,
        isLiked: false,
        isCollected: false,
        tags: ['艺术', '展览'],
        location: '北京·798艺术区'
      },
      {
        id: 103,
        userId: 3,
        title: '中央公园秋色',
        content: '秋天的中央公园美不胜收，金黄的树叶铺满小径',
        isPrivate: false,
        coverImageUrl: 'https://picsum.photos/id/66/400/200',
        createdAt: '2025-09-13T09:00:00',
        updatedAt: '2025-09-13T09:00:00',
        nickname: '自然探索者',
        avatarUrl: 'https://picsum.photos/id/66/100/100',
        likes: 123,
        collects: 32,
        comments: 8,
        isLiked: false,
        isCollected: false,
        tags: ['自然', '摄影'],
        location: '北京·中央公园'
      }
    ]
    
    currentLocation.value = '北京市朝阳区'
  } catch (error) {
    console.error('更新位置失败:', error)
    currentLocation.value = '定位失败'
  }
}

const loadTrendingTopics = async () => {
  try {
    topicStore.trendingTopics = [
      { id: 'topic-1', title: '周末去哪玩', cover: 'https://picsum.photos/300/200?random=1', notesCount: 2450, participants: 12000 },
      { id: 'topic-2', title: '小众咖啡馆', cover: 'https://picsum.photos/300/200?random=2', notesCount: 1890, participants: 9800 },
      { id: 'topic-3', title: '秋日穿搭', cover: 'https://picsum.photos/300/200?random=3', notesCount: 3420, participants: 15600 }
    ]
  } catch (error) {
    console.error('刷新话题失败:', error)
  }
}

const toggleTag = async (tagId) => {
  if (activeTag.value === tagId) {
    await loadRecommendations()
    return
  }

  activeTag.value = tagId
  try {
    isLoading.value = true
    await noteStore.filterNotesByTag(tagId, 6)
    const tagName = tagStore.tags.find(t => t.id === tagId)?.name
    currentFilter.value = `#${tagName}`
  } catch (error) {
    console.error('标签筛选失败', error)
    await loadRecommendations()
    activeTag.value = null
    currentFilter.value = ''
  } finally {
    isLoading.value = false
  }
}

const clearFilter = () => {
  activeTag.value = null
  currentFilter.value = ''
  loadRecommendations()
}

const handleLike = debounce(async (noteId) => {
  if (!authStore.isAuthenticated) {
    alert('请先登录再进行点赞操作')
    return
  }
  
  if (isLoading.value) return
  
  try {
    await noteStore.toggleNoteLike(noteId)
  } catch (error) {
    console.error('点赞失败:', error)
  }
}, 300)

const handleCollect = debounce(async (noteId) => {
  if (!authStore.isAuthenticated) {
    alert('请先登录再进行收藏操作');
    return;
  }
  
  if (isLoading.value) return;
  
  try {
    await noteStore.toggleNoteCollect(noteId);
  } catch (error) {
    console.error('收藏操作失败:', error);
  }
}, 300);

// 弹窗相关方法
const openNoteModal = (noteId) => {
  currentNoteId.value = noteId
  showNoteModal.value = true
}

const closeNoteModal = () => {
  showNoteModal.value = false
}

const handleSearch = () => {
  const query = searchQuery.value.trim()
  if (!query) {
    alert('请输入搜索内容')
    return
  }
  alert(`搜索内容：${query}（后续对接搜索接口）`)
}

const toggleFilter = () => {
  showFilter.value = !showFilter.value
  alert(showFilter.value ? '筛选面板已打开' : '筛选面板已关闭')
}

const viewTopic = (topicId) => {
  alert(`查看话题ID: ${topicId}（后续对接话题页面）`)
}

// 优化图片加载函数
const getOptimizedImageUrl = (url, width = 400, height = 200) => {
  if (!url) return `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/${width}/${height}`
  
  if (url.startsWith('http')) {
    // 添加图片优化参数
    return `${url}?x-oss-process=image/resize,w_${width}/quality,q_80`
  }
  
  return `https://${url}?x-oss-process=image/resize,w_${width}/quality,q_80`
}

const handleImageError = (e) => {
  e.target.src = 'https://picsum.photos/id/1/400/200'
}

const handleSelect = (index) => {
  console.log('导航选择:', index)
}
</script>


<style scoped>
:root {
  --color-primary: #4e54c8;
  --skeleton-bg: #f0f0f0;
  --skeleton-animation: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
}

.discover-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9fafb;
}

.top-nav {
  margin-bottom: 24px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.nav-link {
  text-decoration: none;
  color: inherit;
  display: block;
  width: 100%;
  height: 100%;
}

.search-section {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 24px;
  margin-bottom: 24px;
}

.search-container {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.search-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.search-input:focus {
  border-color: var(--color-primary);
}

.search-input:disabled {
  background-color: #fafafa;
  cursor: not-allowed;
}

.filter-btn {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #f5f5f5;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.filter-btn:disabled {
  background-color: #fafafa;
  cursor: not-allowed;
}

.filter-btn:hover:not(:disabled) {
  background-color: #eee;
}

.trending-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  padding: 8px 16px;
  background-color: #f5f5f5;
  border: none;
  border-radius: 24px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.tag.active {
  background-color: var(--color-primary);
  color: white;
}

.tag:disabled {
  background-color: #fafafa;
  color: #ccc;
  cursor: not-allowed;
}

.tag:hover:not(:disabled) {
  background-color: #eee;
}

.tag.active:hover:not(:disabled) {
  background-color: #3d43b1;
}

.section {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 24px;
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 8px;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.filter-status {
  display: flex;
  align-items: center;
  background-color: #f0f7ff;
  padding: 4px 8px;
  border-radius: 16px;
  font-size: 14px;
  color: var(--color-primary);
}

.clear-filter {
  margin-left: 4px;
  background: none;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: var(--color-primary);
  padding: 4px;
  border-radius: 50%;
}

.clear-filter:hover {
  background-color: #e6f7ff;
}

.refresh-btn, .location-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.3s;
}

.refresh-btn:disabled, .location-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
}

.refresh-btn:hover:not(:disabled), .location-btn:hover:not(:disabled) {
  color: var(--color-primary);
}

.btn-primary {
  padding: 10px 24px;
  background-color: var(--color-primary);
  color: white;
  border: none;
  border-radius: 24px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-primary:disabled {
  background-color: #8cc5ff;
  cursor: not-allowed;
}

.btn-primary:hover:not(:disabled) {
  background-color: #3d43b1;
}

.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.topics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.topic-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.topic-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.topic-image {
  height: 120px;
  overflow: hidden;
}

.topic-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.topic-card:hover .topic-image img {
  transform: scale(1.05);
}

.topic-info {
  padding: 12px;
}

.topic-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 4px 0;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.topic-stats {
  font-size: 12px;
  color: #888;
  margin: 0;
}

.empty-state {
  text-align: center;
  padding: 32px;
  color: #888;
}

.empty-state p {
  margin: 0 0 16px 0;
}

.icon {
  width: 18px;
  height: 18px;
}

/* 骨架屏样式 */
.skeleton {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.skeleton-tag {
  width: 80px;
  height: 32px;
  background: var(--skeleton-bg);
  border-radius: 24px;
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
}

.skeleton-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.skeleton-card {
  height: 320px;
  background: var(--skeleton-bg);
  border-radius: 12px;
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
}

.skeleton-topic {
  height: 180px;
  background: var(--skeleton-bg);
  border-radius: 12px;
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
}

@keyframes skeleton-loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

@media (max-width: 768px) {
  .notes-grid, .topics-grid {
    grid-template-columns: repeat(auto-fill, minmax(100%, 1fr));
  }
  
  .trending-tags {
    overflow-x: auto;
    flex-wrap: nowrap;
    padding-bottom: 8px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>